package dao

import (
	"album/model"
	"context"
	"listenboos-common/db"
	"listenboos-common/db/gorms"
	"listenboos-common/tools"
	"strconv"
	"time"
)

type TrackInfoDao struct {
	conn *gorms.GormConn
}

func (t *TrackInfoDao) SaveTrackInfo(ctx context.Context, conn db.DBConn, data *model.TrackInfo) (int64, error) {
	t.conn = conn.(*gorms.GormConn)
	tx := t.conn.Tx(ctx)
	now := tools.ToTimeString(time.Now().UnixMilli())
	data.CreateTime = now
	data.UpdateTime = now
	err := tx.Save(&data).Error
	return data.Id, err
}

func (t *TrackInfoDao) FindAlbumByUserId(ctx context.Context, userId int64, num int64, size int64) (tracks []*model.TrackInfo, err error) {
	session := t.conn.Session(ctx)
	offset := (num - 1) * size
	err = session.Model(&model.TrackInfo{}).Where("user_id = ? and is_deleted !=1", userId).Limit(int(size)).Offset(int(offset)).Find(&tracks).Error
	if err != nil {
		return nil, err
	}
	return tracks, nil
}
func (d *TrackInfoDao) FindAlbumByIdAndUserId(ctx context.Context, trackId int64) (track *model.TrackInfo, err error) {
	session := d.conn.Session(ctx)
	err = session.Model(&model.TrackInfo{}).Where("id = ?  and is_deleted !=1", trackId).Limit(1).Take(&track).Error
	if err != nil {
		return nil, err
	}
	return track, nil
}
func (d *TrackInfoDao) DeleteTrackInfo(ctx context.Context, conn db.DBConn, trackId int64, userId int64) error {
	data := model.AlbumInfo{}
	d.conn = conn.(*gorms.GormConn)
	tx := d.conn.Tx(ctx)
	now := tools.ToTimeString(time.Now().UnixMilli())
	data.UpdateTime = now
	err := tx.Model(&model.TrackInfo{}).Where("id = ? and user_id = ?", trackId, userId).Update("is_deleted", 1).Error
	return err
}
func NewTrackInfoDao(db *db.ListenDB) *TrackInfoDao {
	return &TrackInfoDao{
		conn: gorms.New(db.Conn),
	}
}
func (d *TrackInfoDao) FindTrackInCount(ctx context.Context, trackId int64, trackCount int64) (ts []*model.TrackInfo, err error) {
	session := d.conn.Session(ctx)
	err = session.Model(&model.TrackInfo{}).Where("id > ?  and is_deleted !=1", trackId).Limit(int(trackCount)).Take(&ts).Error
	if err != nil {
		return nil, err
	}
	return ts, nil
}
func (d *TrackInfoDao) FindTrackByAlbumId(ctx context.Context, albumId int64, pageNo string, pageSize string) (tracks []*model.TrackInfo, current int64, Size int64, total, pages int64, err error) {
	session := d.conn.Session(ctx)
	page, _ := strconv.Atoi(pageNo)
	size, _ := strconv.Atoi(pageSize)
	var offset int
	offset = (page - 1) * size
	err = session.Model(&model.TrackInfo{}).Where("album_id =? and is_deleted !=1", albumId).Offset(offset).Limit(size).Find(&tracks).Error
	if err != nil {
		return nil, 0, 0, 0, 0, err
	}
	err = session.Model(&model.TrackInfo{}).Count(&total).Error
	if err != nil {
		return nil, 0, 0, 0, 0, err
	}
	pages = total / 10
	return tracks, int64(page), int64(size), total, pages, nil
}
